/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.generator.template.impl;

import com.lambkit.generator.template.TemplateEngine;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.FileResourceLoader;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.util.Map;

public class BeetleTemplateEngine extends TemplateEngine {
	@Override
	public String execute(String templateFolder, String templatePath, String templateType, Map<String, Object> templateModel) {
		String res = null;
		try {
			Configuration cfg = Configuration.defaultConfiguration();
			if("class".equalsIgnoreCase(templateType)) {
				templateFolder = templateFolder.startsWith("class:/") ? templateFolder.substring(6) : templateFolder;
				templateFolder = templateFolder.startsWith("//") ? templateFolder.substring(1) : templateFolder;
				ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(templateFolder);
				GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
				Template template = gt.getTemplate(templatePath);
				template.binding(templateModel);
				res = template.render();
			} else {
				//String folderpath = getFolderPath(templateFolder);
				//String filename = getFileName(templateFolder);
				FileResourceLoader resourceLoader = new FileResourceLoader(templateFolder);
				GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
				Template template = gt.getTemplate(templatePath);//templateFolder
				template.binding(templateModel);
				res = template.render();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	@Override
	public String execute(String templateContent, Map<String, Object> templateModel) {
		String res = null;
		try {
			Configuration cfg = Configuration.defaultConfiguration();
			StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
			GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
			Template template = gt.getTemplate(templateContent);
			template.binding(templateModel);
			res = template.render();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return res;
	}
}
